<template>
  <el-container class="page" v-loading.fullscreen.lock="loading">
    <div class="page-head">
      <el-row>
        <el-col :span="4">
          <span>合单号：</span>
          <span>{{ magerInfo.waybillNo }}</span>
        </el-col>
        <el-col :span="4">
          <span>总重量（KG）：</span>
          <span>{{ info.actualWeight }}</span>
        </el-col>
        <el-col :span="4">
          <span>总体积（CMB）：</span>
          <span>{{ info.grossVolume }}</span>
        </el-col>
        <el-col :span="4">
          <span>总计费重（KG）：</span>
          <span>{{ magerInfo.inStockChargedWeight }}</span>
        </el-col>
        <el-col :span="4">
          <span>总体积重：</span>
          <span>{{ magerInfo.inStockVolumeWeight }}</span>
        </el-col>
        <el-col :span="4">
          <span>总件数：</span>
          <span>{{ info.boxCount }}</span>
        </el-col>
      </el-row>
    </div>
    <el-main>
      <el-card>
        <div slot="header" class="clearfix ">
          <div class="flex justify-between">
            <span>调整出库计划</span>
            <div>
              <el-select
                filterable
                v-model="shippingWay"
                placeholder="请选择物流方式"
                size="mini"
                disabled
              >
                <el-option label="FCL" value="FCL"></el-option>
                <el-option label="LCL" value="LCL"></el-option>
                <el-option label="AIR" value="AIR"></el-option>
              </el-select>
              <el-button type="success" size="mini" @click="saveInfo">
                保存
              </el-button>
            </div>
          </div>
        </div>
        <el-table
          class="table-box"
          :border="true"
          :data="tableData"
          style="width: 100%"
          size="mini"
        >
          <el-table-column type="index" label="序号" />
          <!-- 遍历col -->
          <el-table-column
            v-for="column in tableColumns"
            :key="column.prop"
            :auto-fit="true"
            :fit-header="true"
            :show-overflow-tooltip="true"
            :prop="column.prop"
            :label="column.label"
          >
            <template slot-scope="scope">
              <template v-if="column.prop === 'status'">
                {{ m(waybillStatusSource[scope.row[column.prop]]) }}
              </template>
              <template v-else-if="column.prop === 'inStockChannel'">
                {{ instockChannelSource[scope.row[column.prop]] }}
              </template>
              <template v-else-if="column.prop === 'channelCapacity'">
                <template v-if="scope.row[column.prop]">
                  <span
                    v-for="item in scope.row[column.prop].split(',')"
                    :key="item"
                  >
                    {{ channelAbilitySource[item] }}
                  </span>
                </template>
              </template>
              <template v-else-if="column.prop === 'label'">
                <!-- {{ endDeliveryLabelMap[scope.row.waybillNo] }} -->
                <el-input v-model.trim="scope.row[column.prop]" size="mini" />
              </template>
              <template v-else-if="column.prop === 'customerId'">
                {{ customerNameShortSource[scope.row[column.prop]] }}
              </template>
              <template v-else-if="column.prop === 'isClearance'">
                {{ scope.row[column.prop] === 1 ? "是" : "否" }}
              </template>
              <template v-else>
                {{ scope.row[column.prop] }}
              </template>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="50">
            <template slot-scope="scope">
              <i
                class="el-icon-remove text-red text-lg pointer"
                @click="delRow(scope)"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <el-card class="margin-top">
        <div>
          <el-form
            ref="searchForm"
            :model="searchForm"
            label-width="80px"
            size="mini"
          >
            <el-row>
              <el-col :span="5">
                <el-form-item label="运单号" prop="desc">
                  <el-input
                    type="textarea"
                    v-model="searchForm.waybillNo"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="入库渠道">
                  <el-select
                    filterable
                    v-model="searchForm.inStockChannel"
                    placeholder="请选择入库渠道"
                  >
                    <el-option
                      v-for="(item, value) in instockChannelSource"
                      :key="value"
                      :label="item"
                      :value="value"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="目的国家">
                  <el-select
                    filterable
                    v-model="searchForm.countryId"
                    placeholder="请选择目的国家"
                  >
                    <el-option
                      v-for="(item, value) in countrySource"
                      :key="value"
                      :label="item"
                      :value="value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="渠道能力">
                  <el-select
                    multiple
                    v-model="searchForm.channelCapacity"
                    placeholder="请选择渠道能力"
                  >
                    <el-option
                      v-for="(item, value) in channelAbilitySource"
                      :key="value"
                      :label="item"
                      :value="value"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="仓库代码">
                  <el-input v-model="searchForm.dispatchAddressCode"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="运单状态">
                  <el-select
                    v-model="searchForm.status"
                    placeholder="请选择运单状态"
                  >
                    <el-option
                      v-for="(item, value) in waybillStatusSource"
                      :key="value"
                      :label="m(item)"
                      :value="value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="4">
                <el-form-item>
                  <el-button size="mini" type="primary" @click="toSearch"
                    >搜索</el-button
                  >
                </el-form-item>
                <el-form-item>
                  <el-button size="mini" type="info" @click="toReset"
                    >重置</el-button
                  >
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <el-table
          class="table-box"
          :border="true"
          :data="searchList"
          style="width: 100%"
          size="mini"
        >
          <el-table-column type="index" label="序号" />
          <!-- 遍历col -->
          <el-table-column
            v-for="column in columns"
            :key="column.prop"
            :auto-fit="true"
            :fit-header="true"
            :show-overflow-tooltip="true"
            :prop="column.prop"
            :label="column.label"
          >
            <template slot-scope="scope">
              <template v-if="column.prop === 'status'">
                {{ m(waybillStatusSource[scope.row[column.prop]]) }}
              </template>
              <template v-else-if="column.prop === 'inStockChannel'">
                {{ instockChannelSource[scope.row[column.prop]] }}
              </template>
              <template v-else-if="column.prop === 'channelCapacity'">
                <template v-if="scope.row[column.prop]">
                  <span
                    v-for="item in scope.row[column.prop].split(',')"
                    :key="item"
                  >
                    {{ channelAbilitySource[item] }}
                  </span>
                </template>
              </template>

              <template v-else-if="column.prop === 'customerId'">
                {{ customerNameShortSource[scope.row[column.prop]] }}
              </template>
              <template v-else-if="column.prop === 'isClearance'">
                {{ scope.row[column.prop] === 1 ? "是" : "否" }}
              </template>
              <template v-else>
                {{ scope.row[column.prop] }}
              </template>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="50">
            <template slot-scope="scope">
              <i
                class="el-icon-circle-plus text-green text-lg pointer"
                @click="addRow(scope)"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-main>

    <el-footer>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100, 200]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageTotal"
      >
      </el-pagination>
    </el-footer>

    <el-dialog title="选择分单" :visible.sync="selectSingleNo" width="30%">
      <el-form :model="singleNoform" size="mini">
        <el-form-item label="分单：">
          <el-radio-group v-model="singleNoform.waybillSingleNo">
            <el-radio
              v-for="(item, index) in waybillSingleNoList"
              :label="item"
              :key="index"
              class="margin-left"
            >
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="selectSingleNo = false">取 消</el-button>
        <el-button type="primary" @click="selectSingleNo = false"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </el-container>
</template>

<script>
import { clone } from "@/utils/clone";
import { ajax } from "@/store/yg/common/utils";
import axios from "axios";
import { m } from "@/store/yg/common/local";
import * as constant from "@/store/yg/common/constant";
export default {
  data() {
    return {
      loading: false,
      selectSingleNo: false,
      currentPage: 1,
      pageTotal: 0,
      pageSize: 20,
      singleNoform: {
        waybillSingleNo: ""
      },
      tableData: [],
      oldTableData: [],
      searchList: [],
      searchForm: {
        waybillNo: "",
        inStockChannel: "",
        channelCapacity: "",
        status: "",
        countryId: "",
        dispatchAddressCode: ""
      },
      shippingWay: "",

      tableColumns: [
        {
          prop: "waybillNo",
          label: "运单号"
        },
        {
          prop: "waybillSingleNo",
          label: "分单号"
        },
        {
          prop: "inStockActualWeight",
          label: "实重"
        },
        {
          prop: "inStockVolume",
          label: "体积"
        },
        {
          prop: "inStockChargedWeight",
          label: "计费重"
        },
        {
          prop: "inStockVolumeWeight",
          label: "体积重"
        },
        {
          prop: "inStockTotalPackages",
          label: "件数"
        },
        {
          prop: "inStockTime",
          label: "入库时间"
        },
        {
          prop: "status",
          label: "状态"
        },
        // {
        //   prop: "",
        //   label: "品名"
        // },
        {
          prop: "inStockChannel",
          label: "入库渠道"
        },
        {
          prop: "dispatchAddressCode",
          label: "仓库"
        },
        {
          prop: "provinceId",
          label: "邮编"
        },
        {
          prop: "label",
          label: "标签"
        },
        {
          prop: "channelCapacity",
          label: "渠道能力"
        },
        {
          prop: "isClearance",
          label: "是否报关",
          type: "boolean"
        },
        {
          prop: "storageLocation",
          label: "库位"
        },
        {
          prop: "customerId",
          label: "客户简称"
        }
      ],
      columns: [
        {
          prop: "waybillNo",
          label: "运单号"
        },
        {
          prop: "inStockActualWeight",
          label: "实重"
        },
        {
          prop: "inStockVolume",
          label: "体积"
        },
        {
          prop: "inStockChargedWeight",
          label: "计费重"
        },
        {
          prop: "inStockVolumeWeight",
          label: "体积重"
        },
        {
          prop: "inStockTotalPackages",
          label: "件数"
        },
        {
          prop: "inStockTime",
          label: "入库时间"
        },
        {
          prop: "status",
          label: "状态"
        },
        // {
        //   prop: "",
        //   label: "品名"
        // },
        {
          prop: "inStockChannel",
          label: "入库渠道"
        },
        {
          prop: "dispatchAddressCode",
          label: "仓库"
        },
        {
          prop: "provinceId",
          label: "邮编"
        },

        {
          prop: "channelCapacity",
          label: "渠道能力"
        },
        {
          prop: "isClearance",
          label: "是否报关",
          type: "boolean"
        },
        {
          prop: "storageLocation",
          label: "库位"
        },
        {
          prop: "customerId",
          label: "客户简称"
        }
      ],
      customerNameShortSource: {},
      waybillStatusSource: {},
      instockChannelSource: {},
      channelAbilitySource: {},
      waybillNoEndLabelMap: {},
      countrySource: {},
      info: {},
      magerInfo: {},
      waybillSingleNoList: [],
      shippingWayList: ["AIR", "ZX"]
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    async init() {
      // const data = await ajax("getWaybillList", {
      //   id: parseInt(this.$route.query.pid)
      // });
      this.loading = true;
      this.customerNameShortSource = await this.getSource(
        "customerNameShortSource"
      );
      this.waybillStatusSource = await this.getSource("waybillStatusSource");
      this.instockChannelSource = await this.getSource("instockChannelSource");
      this.channelAbilitySource = await this.getSource("channelAbilitySource");
      this.countrySource = await this.getSource("countrySource");
      this.getInfo();
    },
    async getInfo() {
      this.loading = true;
      const { code, data, data2, data3 } = await ajax(
        "findOutStockPlanDetails",
        {
          id: Number(this.$route.query.waybillId)
        }
      );
      console.log("data :>> ", data);
      this.toSearch();
      if (code === 200) {
        const arr = [];
        for (let i of data) {
          if (i.waybillSingleNo) {
            arr.push(i.waybillSingleNo);
          }
          this.$set(i, "label", "");
          for (let j in data2.endDeliveryLabelMap) {
            if (i.waybillNo === j) {
              this.$set(i, "label", data2.endDeliveryLabelMap[j]);
            }
          }
        }
        this.tableData = data;
        // 分单号 arr
        this.waybillSingleNoList = [...new Set(arr)];
        // 原始数据 用于删除做对比
        this.oldTableData = clone(data);
        // 合单信息
        this.magerInfo = data3;

        this.info.boxCount = data2.boxCount;
        this.info.actualWeight = data2.actualWeight;
        this.info.grossVolume = Math.round(data2.grossVolume * 1000) / 1000;
        this.shippingWay = this.magerInfo.shippingWay;
      } else {
        this.$message.error("获取数据失败");
        this.loading = false;
      }
    },
    async getWaybillList() {
      this.loading = true;
      const params = clone(
        Object.assign(this.searchForm, {
          index: this.currentPage,
          size: this.pageSize
        })
      );
      params.channelCapacity = params.channelCapacity.join(",");
    },

    async getSource(name) {
      const uri = "/api/entry/source?bean=" + name;
      const { data } = await axios.post(constant.API_SERVER + uri);
      return data;
    },
    m(k) {
      return m(k, true);
    },
    async saveInfo() {
      if (!this.shippingWay) {
        this.$message.error("请选择物流方式！");
        return;
      }
      this.loading = true;
      const arr = [];
      const obj = {};
      const labelMap = {};
      for (let s of this.tableData) {
        arr.push(s.waybillNo);
        labelMap[s.waybillNo] = s.label;
        for (let i of this.oldTableData) {
          if (i.id !== s.id) {
            if (s.waybillSingleNo && !obj[s.waybillNo]) {
              obj[s.waybillNo] = s.waybillSingleNo;
            }
          }
        }
      }

      const params = {};
      params["id"] = this.magerInfo.id; //合单id;
      params["shippingWay"] = this.shippingWay; //物流方式;
      params["waybillNos"] = arr; //合单列表现有所有运单的运单号;
      params["waybillNoSingleRelationShipMap"] = obj;
      params["waybillNoEndLabelMap"] = labelMap;
      console.log("params :>> ", params);
      // return;
      const { code, message } = await ajax("planSaveSeaAirMerge", params); //分单信息map（key:运单号，value:分单号）;

      if (code === 200) {
        this.$message.success("保存成功！");
        this.getInfo();
      } else {
        this.$message.error(message || "保存失败！");
        this.loading = false;
      }
    },
    async toSearch() {
      this.loading = true;
      const params = clone(
        Object.assign(this.searchForm, {
          index: this.currentPage,
          size: this.pageSize
        })
      );
      params.channelCapacity = params.channelCapacity.join(",");
      const data = await ajax("getWaybillList", params);
      this.searchList = data;

      const data2 = await ajax("getWaybillListCount", params);
      this.pageTotal = data2;
      this.loading = false;
    },
    toReset() {
      this.searchForm = {
        waybillNo: "",
        inStockChannel: "",
        channelCapacity: "",
        status: "",
        countryId: "",
        dispatchAddressCode: ""
      };
    },
    async delRow(s) {
      const target = this.oldTableData.find(x => x.id === s.row.id);
      const row = clone(s.row);
      this.$confirm("确定移除当前运单?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          // 原始数据存在，通过接口删除
          if (target) {
            const { code, message } = ajax("planUpdateWaybillMergeId", {
              ids: [s.row.id],
              waybillId: this.magerInfo.id
            });
            if (code === 200) {
              this.$message.success("删除成功！");
              this.tableData.splice(s.$index, 1);
            } else {
              this.$message.error(message || "删除失败！");
            }
          } else {
            // 不通过接口
            const arr = clone(this.searchList);
            row.waybillSingleNo = "";
            arr.push(row);
            this.searchList = arr;
            this.tableData.splice(s.$index, 1);
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    addRow(s) {
      // this.selectSingleNo = true;
      // return;
      const row = clone(s.row);
      console.log("row :>> ", row);
      const magerTarget = this.shippingWayList.find(x =>
        x === this.magerInfo.shippingWay ? true : false
      );
      const subTarget = this.shippingWayList.find(x =>
        x === row.shippingWay ? true : false
      );
      if (magerTarget != subTarget) {
        this.$message.error("请选择对应运输方式的运单！");
        return;
      }
      // if (row.shippingWay != this.magerInfo.shippingWay) {
      //   this.$message.error("请选择对应运输方式的运单！");
      //   return;
      // }
      const arr = clone(this.tableData);
      if (this.waybillSingleNoList.length > 1) {
        this.selectSingleNo = true;
      } else {
        row.waybillSingleNo = "";
        if (this.waybillSingleNoList.length === 1) {
          row.waybillSingleNo = this.waybillSingleNoList[0];
        }
        arr.push(row);
        this.tableData = arr;
      }
      this.searchList.splice(s.$index, 1);
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.toSearch();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.toSearch();
    }
  }
};
</script>

<style lang="scss" scoped>
.page {
  .page-head {
    position: fixed;
    top: 20px;
    width: 50vw;
  }

  .el-footer {
    height: 30px !important;
  }
}
</style>
